package org.tao.lightningmq.common.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.tao.lightningmq.common.constants.BrokerConstants;

import java.util.List;

/**
 * @Author lht
 * @date 2025/1/7 - 15:05
 * @description:
 */
public class TcpMsgDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        // 读取的起始位置，用于发生拆包时偏移量回滚
        int startIdx = byteBuf.readerIndex();
        if (byteBuf.readableBytes() > TcpMsg.BASE_LEN) {
            if (byteBuf.readShort() != BrokerConstants.DEFAULT_MAGIC_NUM) {
                channelHandlerContext.close();
                return;
            }
            int code = byteBuf.readInt();
            int len = byteBuf.readInt();
            int readableByteLen = byteBuf.readableBytes();
            // 判断是否发生拆包，如果发生拆包则回滚读取位置，等待下一次读取
            if (readableByteLen < len) {
                byteBuf.readerIndex(startIdx);
                return;
            }
            byte[] body = new byte[len];
            byteBuf.readBytes(body);
            TcpMsg tcpMsg = new TcpMsg(code, body);
            list.add(tcpMsg);
        }
    }
}
